package com.shengyijie.activity.tab.user;
  

import org.apache.http.HttpResponse;

import com.shengyijie.activity.MainActivity;
import com.shengyijie.activity.R;      
import com.shengyijie.activity.UserTabActivity;
import com.shengyijie.adapter.view.AlertBox;
import com.shengyijie.adapter.view.AlertBox.OnCanceledListener;
import com.shengyijie.context.ContextApplication;
import com.shengyijie.model.http.HttpConnectApi;
import com.shengyijie.model.json.JsonParser;
import com.shengyijie.model.object.baseobject.User;
import com.shengyijie.util.Utility;

import android.app.Activity; 
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener; 
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class EnterpriseActivity extends Activity implements OnClickListener{ 
	  
	 private ImageButton tabHome;
	 private ImageButton tabCategory;
	 private ImageButton tabRecommended;
	 private ImageButton tabUser;
	 private ImageButton tabMore;
	 public Task task;  
	 private HttpConnectApi httpConnect;
	 private AlertBox mypDialog;
	 
	 private TextView user_name;
	 private TextView count;
	 private TextView p_name;
	 private TextView p_hangye;
	 private TextView p_cname;
	 private TextView p_type;
	 private TextView p_des; 
	 
	 private RelativeLayout gb;
	  
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState); 
         requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); 
         setContentView(R.layout.enterprise);
         getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,      // 注意顺序
                 R.layout.title);
         initView();
         if( ContextApplication.isEnterprise){
        	 new AlertDialog.Builder(EnterpriseActivity.this).setTitle("提示")
			    .setMessage("尊敬的生意街企业会员，您好！由于您尚未发布招商项目，请到http://www.shengyijie.net/，用注册账号登陆生意街企业中心发布招商项目。以后您可以登录生意街手机客户端，随时随地关注招商项目的最新留言情况！谢谢使用！")
			    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					 
				}
			  }) 
			  .show();
        	 user_name.setText(ContextApplication.user.getUser_name());
        	 ContextApplication.isEnterprise=false;
         }else
            getRecommededList();
    }  
    public void initView(){   
    	TextView title=(TextView) this.findViewById(R.id.title);
		title.setText("企业用户中心"); 
		 
		Button back=(Button) this.findViewById(R.id.back);
		back.setVisibility(View.VISIBLE);
		back.setOnClickListener(this);

		Button exit=(Button) this.findViewById(R.id.right);
		exit.setVisibility(View.VISIBLE);
		exit.setText("退出");
		exit.setOnClickListener(this);
		
		user_name=(TextView) this.findViewById(R.id.name);
		count=(TextView) this.findViewById(R.id.count);
		
		p_name=(TextView) this.findViewById(R.id.pname);
		p_hangye=(TextView) this.findViewById(R.id.hangye);
		p_cname=(TextView) this.findViewById(R.id.cn);
		p_type=(TextView) this.findViewById(R.id.type);
		p_des=(TextView) this.findViewById(R.id.des);
		
		gb=(RelativeLayout) this.findViewById(R.id.gb);
		gb.setOnClickListener(this);
    	
    	tabHome=(ImageButton) this.findViewById(R.id.home);
    	tabCategory=(ImageButton) this.findViewById(R.id.category);
    	tabRecommended=(ImageButton) this.findViewById(R.id.recommended);
    	tabUser=(ImageButton) this.findViewById(R.id.user);
    	tabMore=(ImageButton) this.findViewById(R.id.more);
		try{
		    switch(ContextApplication.prePage){
		       case ContextApplication.PAGE_HOME:
		    	   tabHome.setSelected(true);
			       break;
		       case ContextApplication.PAGE_CATEGORY:
		    	   tabCategory.setSelected(true);
			       break;
		       case ContextApplication.PAGE_RECOMMENDED:
		    	   tabRecommended.setSelected(true);
			       break;
		       case ContextApplication.PAGE_USER:
		    	   tabUser.setSelected(true);
			       break;
		       case ContextApplication.PAGE_MORE:
		    	   tabMore.setSelected(true);
			       break;
		     }
		 }catch(Exception e){}
		
		 tabHome.setOnClickListener(this);
		 tabCategory.setOnClickListener(this);
		 tabRecommended.setOnClickListener(this);
		 tabUser.setOnClickListener(this);
		 tabMore.setOnClickListener(this);
    }
    
    public void getRecommededList(){
    	tabHome.postDelayed(new Runnable() {  
	             public void run() {  
	            	 mypDialog=new AlertBox(EnterpriseActivity.this,EnterpriseActivity.this,findViewById(R.id.ep_page)); 
	            	 mypDialog.setCompletedListener(new OnCanceledListener(){ 
	 					@Override
	 					public void onCanceled() { 
	 						if(task.getStatus()==AsyncTask.Status.RUNNING){
	 				    		 task.cancel(true); 
	 						  }
	 					}});
	            	 task=new Task();  
	        	     task.execute(TASK_LOAD_ITEM); 
	             }  
	         },1);
	  }
    
	@Override
	public void onClick(View v) { 
		
		Bundle bd = new Bundle();
        bd.putString("state", "exit");	
        Intent it = new Intent();
        it.putExtras(bd);
        
		switch(v.getId()){
		
		 
		   case R.id.gb:
			    try{
				   if(haveGb){
					   Intent i=new Intent();
					   i.setClass(this, EnterpriseGBActivity.class);
					   this.startActivityForResult(i, 1);
				   }else{
					   Toast.makeText(this, "对不起，您的项目暂时没有留言", Toast.LENGTH_SHORT).show();
				   }
			    }catch(Exception e){}
			    break;
		       
			   case R.id.home:
				    try{
					   if(ContextApplication.prePage!=ContextApplication.PAGE_HOME){
						   MainActivity.tabhost.setCurrentTab(0);
						   setResult(RESULT_OK, it); 
						   this.finish();
					   }
				    }catch(Exception e){}
				    break;
			     case R.id.category:
					    try{
						   if(ContextApplication.prePage!=ContextApplication.PAGE_CATEGORY){
							   MainActivity.tabhost.setCurrentTab(1);
							   setResult(RESULT_OK, it); 
							   this.finish();
						   }
					    }catch(Exception e){}
					    break;
			     case R.id.recommended:
					    try{
						   if(ContextApplication.prePage!=ContextApplication.PAGE_RECOMMENDED){
							   MainActivity.tabhost.setCurrentTab(2);
							   setResult(RESULT_OK, it); 
							   this.finish();
						   }
					    }catch(Exception e){}
					    break;
			     case R.id.user:
					    try{
						   if(ContextApplication.prePage!=ContextApplication.PAGE_USER){
							   MainActivity.tabhost.setCurrentTab(3);
							   setResult(RESULT_OK, it); 
							   this.finish();
						   }
					    }catch(Exception e){}
					    break;
			     case R.id.more:
					    try{
						   if(ContextApplication.prePage!=ContextApplication.PAGE_MORE){
							   MainActivity.tabhost.setCurrentTab(4);
							   setResult(RESULT_OK, it); 
							   this.finish();
						   }
					    }catch(Exception e){}
					    break;  
			     case R.id.back:
					    try{
						  this.finish();
					    }catch(Exception e){}
					    break;
			     case R.id.right:
					    try{
					    	new AlertDialog.Builder(EnterpriseActivity.this).setTitle("提示")
	            			 .setMessage("您确定要退出登录吗？")
	            			 .setPositiveButton("确定", new DialogInterface.OnClickListener() {
	            				public void onClick(DialogInterface dialog, int whichButton) {
	            					Utility.clearUserSession(EnterpriseActivity.this);
	            					EnterpriseActivity.this.finish();
	            				}
	            			  }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
	          				    public void onClick(DialogInterface dialog, int whichButton) {
	       				     }
	       			  })
	            			  .show();  
					    	
        					 
					    }catch(Exception e){}
					    break;
		}
		
	}
	
	boolean haveGb=false;
	public void setProInfo(){
		try{
		
		user_name.setText(ContextApplication.user.getUser_name());
			
			
			p_name.setText(ContextApplication.project.getPro_name());
			p_hangye.setText(Utility.getIndustryName(ContextApplication.project.getPro_industry()));
			p_cname.setText(ContextApplication.project.getPro_com_name());
			//p_type.setText(ContextApplication.project.getPro_industry());
			p_des.setText(ContextApplication.project.getPro_about());
			
			if(ContextApplication.guesstBookList!=null&&ContextApplication.guesstBookList.getCount()>0){
				count.setText(ContextApplication.guesstBookList.getCount()+"");
				haveGb=true;
			}else{
				count.setText(0);
				haveGb=false;
			}
		}catch(Exception e){}
		
	}
	 
	  public String doGetProjectDetail(){
	     	String result="pr_fail";
	        httpConnect=HttpConnectApi.getInstance();
	        try { 
	            HttpResponse response=httpConnect.getUserProjectDetail();
	            if (response.getStatusLine().getStatusCode() == 200)
				{ 
	           	    JsonParser jsonParser=JsonParser.getInstance();
	           	    ContextApplication.project=jsonParser.getProgectDetail(response);
	           	    if(ContextApplication.project!=null){ 
	           	    	 result="pr_ok"; 
	           	    } 
				}
	             
	        }catch (Exception e) {} 
	        
	       
	        try {
	        	httpConnect=HttpConnectApi.getInstance();
	            HttpResponse response=httpConnect.getLoginUser(ContextApplication.user.getSession_ID());
	            if (response.getStatusLine().getStatusCode() == 200)
				{ 
	           	    JsonParser jsonParser=JsonParser.getInstance();
	           	    User user = jsonParser.getLoginUser(response); 
	           	    if(user!=null){
	           	    	ContextApplication.user.setUser_name(user.getUser_name());
	           	    	result="pr_ok"; 
	           	    } 
				}
	            
	        }catch (Exception e) {} 
	        
	        try {
	        	httpConnect=HttpConnectApi.getInstance();
	            HttpResponse response=httpConnect.getFindGuseBook(ContextApplication.user.getSession_ID(),"0,15");
	            if (response.getStatusLine().getStatusCode() == 200)
				{ 
	           	    JsonParser jsonParser=JsonParser.getInstance();
	           	    ContextApplication.guesstBookList = jsonParser.getGuesstBookList(response); 
	           	    result="pr_ok"; 
				}
	            
	        }catch (Exception e) {} 
			return result;
	 }
 
	 private final static int ALERT_LOADING=1; 
	 private final static int RESULT_LOAD_ITEMDETAIL_OK=16;
	 private final static int RESULT_LOAD_ITEMDETAIL_FAIL=17; 
	  
	  
	 private final static String TASK_LOAD_ITEM="loaditem";    
	 private final Handler handler = new Handler(Looper.getMainLooper()) {
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
			 	switch (msg.what) { 
				   case ALERT_LOADING: 
					    mypDialog.show();
					    break;  
                    case RESULT_LOAD_ITEMDETAIL_OK:
                  	     mypDialog.dismiss();  
                  	     setProInfo();
					     break; 
                   case RESULT_LOAD_ITEMDETAIL_FAIL:
					     mypDialog.dismiss(); 
					     Toast.makeText(EnterpriseActivity.this, "对不起，暂无数据", Toast.LENGTH_SHORT).show();			               
					     break; 
				}
			}
		};
		
		
	private class Task extends AsyncTask<String, String, String> {
 
		@Override
		protected String doInBackground(String... params) {
			if(params[0].equals(TASK_LOAD_ITEM)){
				return doGetProjectDetail();
			}else
				return ""; 
		} 
		@Override
		protected void onPostExecute(String result) {				
			super.onPostExecute(result);

			if(result.equals("pr_fail")){
				Message msg = Message.obtain();
				msg.what = RESULT_LOAD_ITEMDETAIL_FAIL;
				handler.sendMessage(msg);
			}else if(result.equals("pr_ok")){
				Message msg = Message.obtain();
				msg.what = RESULT_LOAD_ITEMDETAIL_OK;
				handler.sendMessage(msg);
			} 
		} 
		@Override
		protected void onPreExecute() { 
			super.onPreExecute(); 
		    Message msg = Message.obtain();
		    msg.what = ALERT_LOADING;
			handler.sendMessage(msg); 
		} 
		@Override
		protected void onProgressUpdate(String... values) {
			super.onProgressUpdate(values);
		}
	}
	 
	
	public boolean onKeyDown(int keyCode,KeyEvent event) {   
	    if (keyCode == KeyEvent.KEYCODE_BACK) { 
	    	
				 
						try{
					    	new AlertDialog.Builder(EnterpriseActivity.this).setTitle("提示")
	            			 .setMessage("您确定要退出登录吗？")
	            			 .setPositiveButton("确定", new DialogInterface.OnClickListener() {
	            				public void onClick(DialogInterface dialog, int whichButton) {
	            					Utility.clearUserSession(EnterpriseActivity.this);
	            					EnterpriseActivity.this.finish();
	            				}
	            			  }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
	          				    public void onClick(DialogInterface dialog, int whichButton) {
	       				     }
	       			  })
	            			  .show();  
					    	
        					 
					    }catch(Exception e){}
					 return true;    
	     } else
	         return super.onKeyDown(keyCode,event);   
	 }
    
	 protected void onActivityResult(int requestCode, int resultCode, Intent data) {		
		   if(requestCode==1){
				if (resultCode != RESULT_OK) {
					return;
				}
			   try{
			       String state = data.getStringExtra("state");
			       if(state.equals("exit")){
			    	   Bundle bd = new Bundle();
			           bd.putString("state", "exit");	
			           Intent it = new Intent();
			           it.putExtras(bd);
			           setResult(RESULT_OK, it); 
			    	   this.finish();
			       }
			   }
			   catch(Exception e){}
		   }
	 }
}